package com.example.demo.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.demo.exception.ThrowableException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: cafe zhai
 * @Date: 2024/01/22/9:49
 * @Description:
 */
@Controller
@RequestMapping("/file")
@Slf4j
public class SaveFileController {
    /**
     * 测试文件上传-获取页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public ModelAndView show(Model model) {
        HashMap<String, String> map = new HashMap<>();
        map.put("101", "F");
        map.put("202", "05");
        map.put("303", "00");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("message.html");
        modelAndView.addObject("result", map);
        modelAndView.addObject("number", "101");
        return modelAndView;
    }

    /**
     * 测试文件上传-处理文件
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public ModelAndView getFile(Model model, String text1, String text2, @RequestParam("zip-file") MultipartFile inFile) {
        //指定文件保存位置
        File saveFile = new File("D:\\WorkSoftWare");
        //获取上传文件名称
        String fileName = inFile.getOriginalFilename();
        //最终保存路径&文件名
        File file = new File(saveFile.getAbsoluteFile(), fileName);
        try {
            inFile.transferTo(file);
        } catch (IOException e) {
            //错误抛出
            throw new RuntimeException(e);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("success.html");
        //modelAndView.addObject("fileName", fileName);

        return modelAndView;
    }


    private static String methodA() {
        int a = 1;
        int b = 3;
        try {
            b = a / 0;
        } catch (Exception e) {
            throw new ThrowableException("F1101", "MethodA Catch Error", e);
        }
        return String.valueOf(b);
    }

    private String methodB(String name, String addr) {
        if (StringUtils.hasText(name)) {
            String[] split = name.split(",");
            String ss = split[0] + addr;
            System.out.println("result::" + ss);
            return ss;
        }
        return "";
    }

    public static void main(String[] args) {
        List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
        List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
        List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2");
        List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3");
        List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4");
        List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);
        workBookExportExcel(rows);
    }

    private static void hutoolExportExcel(List<List<String>> rows) {
        List<String> row1 = rows.get(0);
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeTest.xlsx");
        writer.passCurrentRow();
        //合并单元格后的标题行，使用默认标题样式
        writer.merge(row1.size() - 1, "测试标题");
        //一次性写出内容，强制输出标题
        writer.write(rows, true);
        //关闭writer，释放内存
        writer.close();
    }

    private static void workBookExportExcel(List<List<String>> rows) {
        //文件输出流
        FileOutputStream fileOutputStream = null;
        //工作簿
        XSSFWorkbook xss = null;
        try {
            //创建文件
            File file = new File("d:/workBookTest.xlsx");
            file.createNewFile();
            //打开文件
            fileOutputStream = new FileOutputStream(file);
            xss = new XSSFWorkbook();
            //创建工作表
            XSSFSheet sheet = xss.createSheet("sheet");
            //遍历行
            for (int i = 0; i < 4; i++) {
                //获取行
                List<String> ss = rows.get(i);
                //创建行(顶部空一行)
                XSSFRow row = sheet.createRow(i + 1);
                //遍历列
                for (int j = 0; j < 4; j++) {
                    //创建单元格
                    XSSFCell cell = row.createCell(j);
                    //设置值
                    cell.setCellValue(ss.get(j));
                }
            }
            //写入文件
            xss.write(fileOutputStream);
        } catch (FileNotFoundException e) {
            //文件未找到异常
            throw new RuntimeException(e);
        } catch (IOException e) {
            //IO异常
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    //关闭资源异常
                    e.printStackTrace();
                }
            }
            if (xss != null) {
                try {
                    xss.close();
                } catch (IOException e) {
                    //关闭资源异常
                    e.printStackTrace();
                }
            }
        }
    }

}
